package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 获取静态资源的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolatePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolatePath.replaceAll("\\\\","/") + path;
    }

    /**
     * 静态文件输入流，通过输出流输出
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResouce(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while (count == 0){
            count = inputStream.available();
        }

        int resourceSize = count;

        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        int written = 0;
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while (written < resourceSize){
            if( (written + byteSize) > resourceSize){
                byteSize = resourceSize - written;
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }

        outputStream.close();
        inputStream.close();
    }

}
